<template>
  <div class="app-container">
    <el-form ref="noticedemandapprovalRef" :model="formData" :rules="rules" label-width="140px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="立案号" prop="caseId">
            <el-select
              v-model="formData.caseId"
              placeholder="请选择立案号"
              :disabled="disabled || isFlow"
              clearable
              @change="handleCase">
              <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="听证告知书文号" prop="hearingNoticeNo">
            <el-input v-model="formData.hearingNoticeNo" disabled placeholder="请输入听证告知书文号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="当事人名称" prop="partyName">
            <el-input v-model="formData.partyName" disabled placeholder="请输入当事人名称" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="案由" prop="caseCause">
            <el-input v-model="formData.caseCause" disabled placeholder="请输入案由" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="听证申请时间" :rules="rules.requestTime" prop="requestTime">
            <el-date-picker
              v-model="formData.requestTime"
              type="date"
              placeholder="请选择时间"
              :disabled="disabled || isFlow"
              :value-format="'YYYY-MM-DD'" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              :disabled="disabled || isFlow"
              type="textarea"
              :rows="3"
              placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件上传" :rules="rules.files" prop="files">
            <imageUpload v-model="formData.files" :disabled="disabled || isFlow" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, watch, onBeforeUnmount } from 'vue'
import {
  getHearingRequest,
  addHearingRequest,
  updateHearingRequest,
  getCaseList,
  submitHearingRequest,
  reviewHearingRequest,
  getContent,
} from '@/api/hearingNotice/application.js'
import { registrationcaseDetail } from '@/api/filingReview/register'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance()

// Props
const props = defineProps({
  id: {
    type: [String, Number],
    default: null,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  isFlow: {
    type: Boolean,
    default: false,
  },
})

const router = useRouter()

// Emits
const emit = defineEmits(['handleSubmit'])

// Form data
const formData = ref({
  id: null,
  caseId: null,
  caseNo: null,
  partyName: null,
  caseCause: null,
  remark: null,
  caseCause: null,
  requestTime: null,
})
// Form validation rules
const rules = {
  partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
  caseId: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  hearingNoticeNo: [{ required: true, message: '听证告知书文号不能为空', trigger: ['blur', 'change'] }],
  requestTime: [{ required: true, message: '听证申请时间不能为空', trigger: ['blur', 'change'] }],
  caseCause: [{ required: true, message: '案由不能为空', trigger: ['blur', 'change'] }],
  files: [{ required: true, message: '请上传附件', trigger: 'change' }],
}
// Refs
const noticedemandapprovalRef = ref()

// Methods
const reset = () => {
  formData.value = {
    id: null,
    caseId: null,
    caseNo: null,
    partyName: null,
    remark: null,
    hearingNoticeNo: null,
    hearingNoticeApprovalResultId: null,
    requestTime: null,
    caseCause: null,
    files: [],
  }
  proxy.resetForm('noticedemandapprovalRef')
}

// Get detail data
const getDetail = async id => {
  reset()
  if (id) {
    try {
      const res = await getHearingRequest(id)
      if (!res?.data) return
      formData.value = res.data
    } catch (error) {
      console.error('获取详情失败:', error)
    }
  }
}

const handleCase = async val => {
  return new Promise(async (resolve, reject) => {
    if (!val) {
      formData.value.caseNo = ''
      formData.value.partyName = ''
      formData.value.caseCause = ''
      formData.value.hearingNoticeNo = ''
      formData.value.hearingNoticeApprovalResultId = ''
      formData.value.requestTime = ''
      return
    }
    const res = await registrationcaseDetail(val)
    const { partyName } = res.data
    formData.value.caseNo = res.data.caseNo
    formData.value.requestTime = res.data.requestTime

    formData.value.partyName = partyName
    formData.value.caseCause = res.data.caseCause
    const res2 = await getContent(val)
    formData.value.hearingNoticeNo = res2.data.hearingNoticeNo
    formData.value.hearingNoticeApprovalResultId = res2.data.hearingNoticeApprovalResultId

    resolve()
  })
}

// Submit form
const submitForm = async (isDraft = false) => {
  try {
    await noticedemandapprovalRef.value.validate()

    let result
    if (isDraft) {
      // 草稿
      if (formData.value.id) {
        result = await updateHearingRequest(formData.value)
      } else {
        result = await addHearingRequest(formData.value)
      }
    } else {
      // 提交
      result = await submitHearingRequest(formData.value)
    }

    ElMessage.success(isDraft ? '保存草稿成功' : '提交成功')
    emit('handleSubmit', result)
    return result
  } catch (error) {
    console.error('提交失败:', error)
    return false
  }
}

// 待办页面 提交 / 退回
const handleSubmitReview = async form => {
  await reviewHearingRequest({
    ...form,
    id: props.editId || props.id,
  })
  proxy.$modal.msgSuccess('操作成功')
  router.back()
}

// 待办页面获取批注列表
const timer = ref(null)
const getAnnotationList = () => {
  return new Promise((resolve, reject) => {
    timer.value = setInterval(() => {
      if (formData.value.id) {
        clearInterval(timer.value)
        resolve({ ...formData.value })
      } else {
        resolve([])
      }
    }, 500)
  })
}

// Watch props.id change
watch(
  () => props.id,
  newVal => {
    if (newVal) {
      getDetail(newVal)
    } else {
      reset()
    }
    handleCaseList()
  },
  { immediate: true }
)

const numberList = ref([])
async function handleCaseList() {
  const res = await getCaseList()
  numberList.value = res.data.map(item => ({
    label: item.caseNo,
    value: item.id,
  }))
}
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})
// Expose methods
defineExpose({
  submitForm,
  reset,
  formData,
  getAnnotationList,
  handleSubmitReview,
  formRef: noticedemandapprovalRef,
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
